#include <net/if.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define PORT 8888
#define BUF_SIZE 1024
#define MGROUP "224.2.2.2"  //多播地址

int main() {
    int server_socket;
    struct sockaddr_in server_addr;
    char buf[BUF_SIZE];

    // 创建UDP套接字并绑定到指定地址和端口
    server_socket = socket(AF_INET, SOCK_DGRAM, 0);
    if (server_socket < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 加入多播组
    struct ip_mreqn mreq;
    inet_pton(AF_INET,MGROUP,&mreq.imr_multiaddr);
    inet_pton(AF_INET,"0.0.0.0",&mreq.imr_address);
    mreq.imr_ifindex = if_nametoindex("eth0");
    
    if (setsockopt(server_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
        perror("setsockopt failed");
        exit(EXIT_FAILURE);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // 绑定到任意地址
    bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr));

    // 等待接收广播消息
    while (1) {
        printf("Waiting for broadcast message...\n");
        struct sockaddr_in client_addr;
        socklen_t client_addr_len = sizeof(client_addr); // 用于接收客户端地址结构体的长度
        int len = recvfrom(server_socket, buf, BUF_SIZE, 0, (struct sockaddr *)&client_addr, &client_addr_len);
        if (len < 0) {
            perror("recvfrom failed");
            continue;
        }
        buf[len] = '\0'; // 添加字符串结束符
        printf("Received message: %s\n", buf);
    }

    // 关闭套接字并退出程序
    close(server_socket);
    return 0;
}
